<template>
  <div class="alerts-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon color="#F56C6C"><AlarmClock /></el-icon>
            <span>紧急求救处理</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <!-- 添加用户管理按钮，仅当用户是adminRoot时显示 -->
            <el-button 
              v-if="isAdminRoot" 
              type="success" 
              @click="goToUserManagement"
            >
              <el-icon><User /></el-icon>
              用户管理
            </el-button>
          </div>
        </div>
      </template>
      <!-- 求救列表 -->
      <div class="alerts-list">
        <el-table
          :data="alertsList"
          
          border
          style="width: 100%"
          v-loading="loading"
          :row-class-name="getRowClassName"
        >          
          <!-- <el-table-column prop="userName" label="用户" width="100" /> -->
          
          <!-- 司机信息 -->
          <el-table-column label="司机信息" width="200">
            <template #default="scope">
              <div v-if="scope.row.parsedMsg && scope.row.parsedMsg.driverUser">
                <div>姓名: {{ scope.row.parsedMsg.driverUser.realName || scope.row.parsedMsg.driverUser.nickname }}</div>
                <div v-if="scope.row.parsedMsg.driverInfo">
                  <div>车牌号: {{ scope.row.parsedMsg.driverInfo.vehicleNumber }}</div>
                  <div>车名: {{ scope.row.parsedMsg.driverInfo.vehicleBrand }}</div>
                  <div>车型: {{ scope.row.parsedMsg.driverInfo.vehicleModel }}</div>
                </div>
              </div>
              <span v-else>暂无司机信息</span>
            </template>
          </el-table-column>
          
          <!-- 乘客信息 -->
          <el-table-column label="乘客信息" width="200">
            <template #default="scope">
              <div v-if="scope.row.parsedMsg && scope.row.parsedMsg.sosUser">
                <div>姓名: {{ scope.row.parsedMsg.sosStudentInfo.realName || scope.row.parsedMsg.sosUser.nickname }}</div>
                <div v-if="scope.row.parsedMsg.sosStudentInfo">
                  <div>学校: {{ scope.row.parsedMsg.sosStudentInfo.schoolName }}</div>
                  <div>学号: {{ scope.row.parsedMsg.sosStudentInfo.schoolId }}</div>
                </div>
              </div>
              <span v-else>暂无乘客信息</span>
            </template>
          </el-table-column>
          
          <!-- 行程信息 -->
          <el-table-column label="行程ID" width="180">
            <template #default="scope">
              <div v-if="scope.row.parsedMsg && scope.row.parsedMsg.tripInfoVo">
                <el-tooltip content="点击复制" placement="top" :hide-after="1000">
                  <div class="clickable-id" @click="copyToClipboard(scope.row.parsedMsg.tripInfoVo.id)">
                    {{ scope.row.parsedMsg.tripInfoVo.id}}
                    <el-icon><DocumentCopy /></el-icon>
                  </div>
                </el-tooltip>
              </div>
              <span v-else>无行程信息</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="createTime" label="求救时间" width="180" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === false
              " type="danger">待处理</el-tag>
              <el-tag v-else-if="scope.row.status === true" type="success">已解决</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                type="primary" 
                @click="handleAlert(scope.row)"
                :disabled="scope.row.status === true"
              >
                处理
              </el-button>
              <!-- <el-button 
                size="small" 
                @click="viewLocation(scope.row)"
              >
                位置
              </el-button> -->
              <el-button 
                size="small" 
                @click="viewDetails(scope.row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="处理求救信息"
      width="600px"
    >
      <div class="dialog-content" v-if="currentAlert">
        <div class="alert-info-box">
          <div class="alert-id">
            求救ID: {{ currentAlert.id }}
          </div>
          <div class="alert-user">
            求救用户: {{ currentAlert.userName }} ({{ currentAlert.userType === 'passenger' ? '乘客' : '司机' }})
          </div>
          <div class="alert-time">
            求救时间: {{ currentAlert.createTime }}
          </div>
          <!-- <div class="alert-location">
            求救位置: {{ currentAlert.location }}
          </div> -->
          <!-- <div class="alert-title">
            求救标题: {{ currentAlert.title }}
          </div>
          <div class="alert-desc">
            求救描述: {{ currentAlert.description || '无详细描述' }}
          </div> -->
        </div>

        <el-divider />

        <div class="process-form">
          <el-form :model="processForm" label-width="100px" :rules="processRules" ref="processFormRef">
            <el-form-item label="处理状态" prop="status">
              <el-select v-model="processForm.status" placeholder="请选择处理状态" style="width: 100%">
                <el-option label="处理中" value="processing" />
                <el-option label="已解决" value="resolved" />
                <el-option label="已关闭" value="closed" />
              </el-select>
            </el-form-item>
            <el-form-item label="处理内容" prop="content">
              <el-input
                v-model="processForm.content"
                type="textarea"
                :rows="4"
                placeholder="请输入处理内容"
              />
            </el-form-item>
            <el-form-item label="紧急联系" prop="contact">
              <el-input v-model="processForm.contact" placeholder="请输入紧急联系方式">
                <template #append>
                  <el-button @click="callEmergency">
                    <el-icon><Phone /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 位置查看对话框 -->
    <!-- <el-dialog
      v-model="locationDialogVisible"
      title="求救位置"
      width="800px"
    > -->
      <!-- <div class="location-map" ref="locationMapRef"></div>
    </el-dialog> -->

    <!-- 新增：详情查看对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="求救详细信息"
      width="800px"
    >
      <div class="detail-content" v-if="currentDetail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="求救ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="求救时间">{{ currentDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="currentDetail.status === 'pending'" type="danger">待处理</el-tag>
            <el-tag v-else-if="currentDetail.status === 'processing'" type="warning">处理中</el-tag>
            <el-tag v-else-if="currentDetail.status === 'resolved'" type="success">已解决</el-tag>
            <el-tag v-else-if="currentDetail.status === 'closed'" type="info">已关闭</el-tag>
          </el-descriptions-item>
          <!-- <el-descriptions-item label="位置">{{ currentDetail.location }}</el-descriptions-item> -->
        </el-descriptions>
        
        <el-divider />
        
        <!-- 司机信息 -->
        <el-descriptions v-if="currentDetail.parsedMsg && currentDetail.parsedMsg.driverUser" 
                        title="司机信息" :column="2" border>
          <el-descriptions-item label="司机名称">
            {{ currentDetail.parsedMsg.driverUser.realName || currentDetail.parsedMsg.driverUser.nickname }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentDetail.parsedMsg.driverUser.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="车牌号" v-if="currentDetail.parsedMsg.driverInfo">
            {{ currentDetail.parsedMsg.driverInfo.vehicleNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="车名" v-if="currentDetail.parsedMsg.driverInfo">
            {{ currentDetail.parsedMsg.driverInfo.vehicleBrand }}
          </el-descriptions-item>
          <el-descriptions-item label="车型" v-if="currentDetail.parsedMsg.driverInfo">
            {{ currentDetail.parsedMsg.driverInfo.vehicleModel }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 乘客信息 -->
        <el-descriptions v-if="currentDetail.parsedMsg && currentDetail.parsedMsg.sosUser" 
                        title="乘客信息" :column="2" border>
          <el-descriptions-item label="乘客名称">
            {{ currentDetail.parsedMsg.sosUser.realName || currentDetail.parsedMsg.sosUser.nickname }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentDetail.parsedMsg.sosUser.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="学校" v-if="currentDetail.parsedMsg.sosStudentInfo">
            {{ currentDetail.parsedMsg.sosStudentInfo.realName }}
          </el-descriptions-item>
          <el-descriptions-item label="学号" v-if="currentDetail.parsedMsg.sosStudentInfo">
            {{ currentDetail.parsedMsg.sosStudentInfo.idCardNumber }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 行程信息 -->
        <el-descriptions v-if="currentDetail.parsedMsg && currentDetail.parsedMsg.tripInfoVo" 
                        title="行程信息" :column="2" border>
          <el-descriptions-item label="行程ID">
            <div class="clickable-id" @click="copyToClipboard(currentDetail.parsedMsg.tripInfoVo.id)">
              {{ currentDetail.parsedMsg.tripInfoVo.id }}
              <el-tooltip content="点击复制" placement="top" :hide-after="1000">
                <el-icon><DocumentCopy /></el-icon>
              </el-tooltip>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="预计出发时间">
            {{ currentDetail.parsedMsg.tripInfoVo.estimatedStartTime }}
          </el-descriptions-item>
          <el-descriptions-item label="乘车点">
            {{ currentDetail.parsedMsg.tripInfoVo.startLocation }}
          </el-descriptions-item>
          <el-descriptions-item label="目的地">
            {{ currentDetail.parsedMsg.tripInfoVo.endLocation }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="success" @click="completeProcess" 
            :disabled="!currentDetail || currentDetail.status === 'resolved' || currentDetail.status === 'closed'">
            完成处理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMessageNotifications, processAlert, markAsRead } from '@/api/notification'
import { DocumentCopy, AlarmClock, Refresh, Phone, User } from '@element-plus/icons-vue'
import JSONbig from 'json-bigint'

const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filters = reactive({
  status: '',
  userType: '',
  dateRange: []
})

// 重置筛选条件
const resetFilters = () => {
  filters.status = ''
  filters.userType = ''
  filters.dateRange = []
  searchAlerts()
}

// 搜索求救信息
const searchAlerts = () => {
  loading.value = true
  fetchAlertsList()
}

// 刷新数据
const refreshData = () => {
  fetchAlertsList()
}

// 获取行样式
const getRowClassName = ({ row }) => {
  if (row.status === 'pending') {
    return 'alert-row-pending'
  }
  return ''
}

// 求救列表数据
const alertsList = ref([])

// 获取求救列表数据
const fetchAlertsList = () => {
  loading.value = true
  getMessageNotifications()
    .then(response => {
      if (response.code === 1) {
        // 转换后端数据格式为前端所需格式
        alertsList.value = response.data.map(item => {
          // 处理msg字段，将其转换为对象
          let parsedMsg = {};
          if (item.msg) {
            try {
              // 去除转义字符并使用json-bigint解析JSON，避免大数字丢失精度
              const cleanJsonStr = item.msg.replace(/\\/g, '');
              parsedMsg = JSONbig.parse(cleanJsonStr);
              console.log('解析后的数据:', parsedMsg);  
            } catch (error) {
              console.error('解析JSON失败:', error);
            }
          }
          
          return {
            id: item.id,
            userType: item.fromUserType || (parsedMsg.driverUser ? 'driver' : 'passenger'), // 使用解析后的数据
            userName: item.fromUserName || (parsedMsg.driverUser ? parsedMsg.driverUser.nickname : (parsedMsg.passengerUser ? parsedMsg.passengerUser.nickname : '未知')),
            title: item.title,
            location: item.location || parsedMsg.location || '未知位置',
            detailLocation: item.detailLocation || parsedMsg.detailLocation || item.location || '未知位置',
            description: item.content || parsedMsg.content,
            createTime: item.createTime,
            status: item.isRead || false,
            processRecords: item.processRecords || [],
            parsedMsg: parsedMsg  // 保存解析后的完整数据供后续使用
          }
        })
        total.value = response.data.length
        ElMessage.success('数据已刷新')
      } else {
        ElMessage.error(response.msg || '获取数据失败')
      }
    })
    .catch(error => {
      console.error('获取求救信息失败', error)
      ElMessage.error('获取求救信息失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAlertsList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAlertsList()
}

// 处理求救信息
const dialogVisible = ref(false)
const currentAlert = ref(null)
const processFormRef = ref(null)
const processForm = reactive({
  status: 'processing',
  content: '',
  contact: '110'
})

// 表单验证规则
const processRules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  content: [{ required: true, message: '请输入处理内容', trigger: 'blur' }]
}

// 处理求救请求
const processRequest = (row) => {
  if (!row || !row.id) return;
  
  processAlert(row.id)
    .then(response => {
      if (response.code === 1) {
        // 更新状态为已处理
        row.status = 'resolved';
        
        ElMessage.success('处理成功');
        
        // 刷新列表数据
        fetchAlertsList();
      } else {
        ElMessage.error(response.msg || '处理失败');
      }
    })
    .catch(error => {
      console.error('处理求救信息失败', error);
      ElMessage.error('处理求救信息失败');
    });
}

// 打开处理对话框
const handleAlert = (row) => {
  // 直接处理，无需显示对话框
  processRequest(row);
}

// 提交处理 - 为兼容性保留，但内部调用processRequest
const submitProcess = async () => {
  if (!currentAlert.value) return;
  processRequest(currentAlert.value);
  dialogVisible.value = false;
}

// 查看位置
const locationDialogVisible = ref(false)
const locationMapRef = ref(null)

const viewLocation = (row) => {
  locationDialogVisible.value = true
  // 等待DOM更新后初始化地图
  nextTick(() => {
    // 这里应该集成高德地图API
    // 因为需要引入外部API，这里只做占位处理
    if (locationMapRef.value) {
      locationMapRef.value.innerHTML = `
        <div style="height: 400px; display: flex; justify-content: center; align-items: center; background-color: #f5f7fa; color: #909399;">
          <div>
            <p>此处将显示用户求救位置（需集成高德地图API）</p>
            <p>位置信息: ${row.detailLocation}</p>
          </div>
        </div>
      `
    }
  })
}

// 联系用户
const contactUser = (row) => {
  ElMessageBox.confirm(
    `是否要联系${row.userName}？`,
    '联系用户',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  )
  .then(() => {
    // 模拟联系用户
    ElMessage({
      type: 'success',
      message: `已发起与${row.userName}的通话`
    })
  })
  .catch(() => {})
}

// 联系紧急救援
const callEmergency = () => {
  ElMessageBox.confirm(
    `是否要拨打紧急联系电话${processForm.contact}？`,
    '紧急联系',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(() => {
    // 模拟拨打电话
    ElMessage({
      type: 'success',
      message: `已拨打紧急联系电话: ${processForm.contact}`
    })
  })
  .catch(() => {})
}

// 查看详情
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

const viewDetails = (row) => {
  currentDetail.value = row
  detailDialogVisible.value = true
}

// 完成处理
const completeProcess = () => {
  if (!currentDetail.value || !currentDetail.value.id) return;
  
  processAlert(currentDetail.value.id)
    .then(response => {
      if (response.code === 1) {
        // 更新状态为已处理
        currentDetail.value.status = 'resolved';
        
        ElMessage.success('求救信息已处理');
        detailDialogVisible.value = false;
        
        // 刷新列表数据
        fetchAlertsList();
      } else {
        ElMessage.error(response.msg || '操作失败');
      }
    })
    .catch(error => {
      console.error('处理失败', error);
      ElMessage.error('处理失败');
    });
}

// 添加复制到剪贴板的功能
const copyToClipboard = (text) => {
  if (!text) return
  
  // 创建临时textarea元素
  const textarea = document.createElement('textarea')
  textarea.value = text
  document.body.appendChild(textarea)
  
  // 选择并复制内容
  textarea.select()
  document.execCommand('copy')
  
  // 移除临时元素
  document.body.removeChild(textarea)
  
  // 提示用户
  ElMessage.success('已复制到剪贴板')
}

// 添加用户管理按钮，仅当用户是adminRoot时显示
const isAdminRoot = ref(false)

// 检查当前登录用户是否为adminRoot
const checkAdminRoot = () => {
  // 从localStorage获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  // 判断phone是否为adminRoot
  isAdminRoot.value = userInfo.phone === 'adminRoot'
}

const goToUserManagement = () => {
  // 跳转到用户管理页面
  router.push('/staff/user-management')
}

// 组件挂载后执行
onMounted(() => {
  fetchAlertsList()
  
  // 检查是否有指定的求救ID
  const alertId = route.query.alertId
  if (alertId) {
    const targetAlert = alertsList.value.find(item => item.id === alertId)
    if (targetAlert) {
      handleAlert(targetAlert)
    }
  }

  // 检查是否为管理员
  checkAdminRoot()
})
</script>

<style scoped>
.alerts-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.alerts-list {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.expanded-content {
  padding: 10px 20px;
}

.expanded-item {
  margin-bottom: 10px;
  display: flex;
}

.item-label {
  font-weight: bold;
  width: 100px;
  color: #606266;
}

.item-value {
  flex: 1;
}

.process-record {
  margin-bottom: 5px;
  padding: 5px 0;
  border-bottom: 1px dashed #ebeef5;
  display: flex;
}

.record-time {
  width: 160px;
  color: #909399;
}

.record-operator {
  width: 100px;
  font-weight: bold;
}

.record-action {
  flex: 1;
}

.alert-row-pending {
  background-color: #fef0f0;
}

.alert-info-box {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.alert-id, .alert-user, .alert-time, .alert-location, .alert-title, .alert-desc {
  margin-bottom: 10px;
}

.location-map {
  height: 400px;
  border-radius: 4px;
  overflow: hidden;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

/* 添加可点击复制ID的样式 */
.clickable-id {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #409EFF;
}

.clickable-id:hover {
  text-decoration: underline;
}

.clickable-id .el-icon {
  margin-left: 5px;
  font-size: 14px;
}
</style> 